import React, { useEffect, useRef, useState } from 'react';
import { useRecoilState } from 'recoil';
import { editorVideo } from '../../../../recoil/editor';
import $style from './style.module.less';
import { PlayOne, VolumeNotice, PauseOne } from '@icon-park/react';
import { EVideoState, IVideoProps } from './types';
import { getHhMmDd } from '../../../../utils/time';
import { VoiceDrag } from './components/VoiceDrag';
import { getVideoFrame } from '../../../../utils/video';

interface IProps {}

export const EditorVideo: React.FC<IProps> = props => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [videoProps, setVideoProps] = useState<IVideoProps>({
    currentTime: 0,
    width: 0,
    height: 0,
    voice: 0,
    duration: 0,
    state: EVideoState.Stop,
  });

  useEffect(() => {
    getVideoFrame();
  }, []);
  const handleCanPlay = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
    const video = e.currentTarget;
    const { videoWidth, videoHeight, duration, currentTime, volume } = video;

    setVideoProps({
      currentTime: currentTime,
      width: videoWidth,
      height: videoHeight,
      voice: 0.5,
      duration: duration,
      state: EVideoState.Stop,
    });
  };

  const handleToggleVideoState = () => {
    const videoEle = videoRef.current;
    const { state } = videoProps;

    if (videoEle) {
      if (state === EVideoState.Play) {
        videoEle?.pause();
        setVideoProps({ ...videoProps, state: EVideoState.Stop });
        return;
      }

      videoEle.play();
      setVideoProps({ ...videoProps, state: EVideoState.Play });
    }
  };

  const handleTimeUpdate = () => {
    const videoEle = videoRef.current;

    if (videoEle) {
      setVideoProps({ ...videoProps, currentTime: videoEle.currentTime });
    }
  };

  const handleVideoEnd = () => {
    const videoEle = videoRef.current;
    if (videoEle) {
      handleToggleVideoState();
    }
  };

  // 鼠标点击时间轴
  const handleClickInlinePro = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const nativeEvent = e.nativeEvent;
    const lineEl = e.currentTarget;
    const { offsetX } = nativeEvent;
    const lineWidth = lineEl.offsetWidth;

    const widthPrecent = offsetX / lineWidth;
    const { duration } = videoProps;
    const currentTime = duration * widthPrecent;
    const videoEle = videoRef.current;

    if (videoEle) {
      videoEle.currentTime = currentTime;
      videoEle.pause();
    }
    setVideoProps({ ...videoProps, state: EVideoState.Stop, currentTime });
  };

  const { currentTime, duration, state } = videoProps;

  const isPlay = state === EVideoState.Play;

  let innerProcessWidthPrecent = (currentTime / duration) * 100;

  // 处理视频元信息：视频结束时currentTime和duration不一致的情况导致进度条不能到底的情况 误差值0.2
  if (Math.abs(duration - currentTime) < 0.2) {
    innerProcessWidthPrecent = 100;
  }

  return (
    <div className={$style.videoWrapper}>
      <div className={$style.videoContentWrapper}>
        <video
          ref={videoRef}
          controls={false}
          src='/demon.mp4'
          x5-playsinline='true'
          webkit-playsinline='true'
          preload='auto'
          // onCanPlay={handleCanPlay}
          onLoadedMetadata={handleCanPlay}
          onTimeUpdate={handleTimeUpdate}
          onEnded={handleVideoEnd}
        />
      </div>
      <div className={$style.controlWrapper}>
        <div className={$style.line} onClick={handleClickInlinePro}>
          <div className={$style.innerProcess} style={{ width: `${innerProcessWidthPrecent}%` }}></div>
        </div>
        <div className={$style.control}>
          <div className={$style.leftWrapper}>
            <div className={$style.videoPlayBtn} onClick={handleToggleVideoState}>
              {!isPlay ? (
                <PlayOne size='20' fill='#fff' theme='filled' />
              ) : (
                <PauseOne size='20' fill='#fff' theme='outline' />
              )}
            </div>
            <span className={$style.text}>
              {getHhMmDd(currentTime)}/{getHhMmDd(duration)}
            </span>
          </div>
          <div className={$style.rightWrapper}>
            <VoiceDrag>
              <VolumeNotice size='20' fill='#fff' theme='filled' />
            </VoiceDrag>
          </div>
        </div>
      </div>
    </div>
  );
};
